//
//  SSDKHeartbeat.m
//  SuperSDK
//
//  Created by 涂俊 on 2017/10/31.
//  Copyright © 2017年 WYHT. All rights reserved.
//

#import "SSDKHeartbeat.h"
#import "SSDKEventKeys.h"
#import "SSDKEventManager.h"
#import "SSDKDataKeys.h"
#import "SuperSDKInst.h"
#import "SSDKUserManager.h"
#import "SSDKUserInfo.h"
#import "SSDKHttpV2Util.h"
#import "SSDKSwitchUtil.h"

#import "SuperSDKPluginTools/SSDKPluginTimerUtil.h"
#import "SuperSDKPluginTools/SSDKPluginDataHelper.h"
#import "SuperSDKPluginTools/SSDKPluginStringUtil.h"

@implementation SSDKHeartbeat

{
    @private
    dispatch_source_t timer;
}

// 缓存上报登录数据的key
static NSString *CACHE_LOGIN_SUBMIT_KEY= @"login_submit";

// 默认心跳间隔时长，单位：秒
static double HEART_BEAT_INTERVAL = 300;

//心跳的地址
static NSString *SDK_HEART_BEAT_PATH = @"/supersdk-web/v2/app/trace/submit";

- (void) initInfo {
    self.isRunning = NO;
    timer = nil;
    [SSDKEventManager addObsver:self selector:@selector(submitData:) name:EVENT_SUBMITDATA object:nil className:@"SSDKHeartbeat"];
    [SSDKEventManager addObsver:self selector:@selector(logout) name:EVENT_LOGOUT object:nil className:@"SSDKHeartbeat"];
    [SSDKEventManager addObsver:self selector:@selector(logout) name:EVENT_FLOAT_LOGOUT object:nil className:@"SSDKHeartbeat"];
}

- (void) submitData:(NSNotification*) notification {
    NSString *ext = [[notification object] objectForKey:SUBMIT_EXT];
    if ([SUBMIT_LOGIN_EVENT isEqualToString:ext]) {
        //第一次登录成功后，启动心跳
        [self start];
    }
}


- (void) logout {
    //登出后，停止心跳
    [self stop];
}


- (void) start {
    if (self.isRunning) {
        return;
    }
    self.isRunning = YES;
    [SSDKSwitchUtil allValueWithDelegate:^(NSDictionary *value) {
        // 只有服务器开关开启，才开启心跳，默认是关闭
        if (![@"true" isEqualToString:[value valueForKey:@"heartbeat_switch"]]) {
            NSLog(@"心跳关闭，不启动!");
            self.isRunning = NO;
            return;
        }
        double timerInterval = HEART_BEAT_INTERVAL;
        NSString *intervalStr = [value valueForKey:@"heartbeat_interval"];
        if (![SSDKPluginStringUtil isEmptyString:intervalStr]) {
            timerInterval = [intervalStr doubleValue];
        }
        timer = [SSDKPluginTimerUtil createTimerWithInterval:timerInterval
                                                      mainThread:NO
                                                        startNow:YES
                                                         handler:^(dispatch_source_t timer) {
                                                             NSMutableDictionary *params = [SSDKPluginDataHelper dataValueWithKey:CACHE_LOGIN_SUBMIT_KEY];
                                                             if (params == nil) {
                                                                 NSLog(@"上报心跳失败，无登录数据 %@", [NSThread currentThread]);
                                                                 return;
                                                             }
                                                             NSLog(@"上报心跳 %@", [NSThread currentThread]);
                                                             //    NSString *url = [@"http://192.168.2.150" stringByAppendingString:SDK_TRACE_PATH];
                                                             NSString *url = [[[SuperSDKInst getInstance] sUrl] stringByAppendingString:SDK_HEART_BEAT_PATH];
                                                             NSMutableDictionary *wrapParams = [[NSMutableDictionary alloc] initWithDictionary:params];
                                                             SSDKUserInfo *user = [[SSDKUserManager getInstance] curUserInfo];
                                                             [wrapParams setValue:@"onLine" forKey:SUBMIT_EXT];// ext必须是onLine
                                                             [wrapParams setValue:[[SuperSDKInst getInstance] appId] forKey:APP_ID];
                                                             [wrapParams setValue:[[SuperSDKInst getInstance] channelId] forKey:CHANNEL_ID];
                                                             [wrapParams setValue:[NSString stringWithFormat:@"%d", [[SuperSDKInst getInstance] serverID]] forKey:SUBMIT_ZONE_ID];
                                                             [wrapParams setValue:[user superSDKUid] forKey:SUPERSDK_UID];
                                                             [wrapParams setValue:[user sdkUid] forKey:SDK_UID];
                                                             [wrapParams setValue:@"IOS" forKey:@"platform"];
                                                             [wrapParams setValue:[[[SuperSDKInst getInstance] clientInfo] valueForKey:SSDK_L_DEVICE_ID] forKey:SSDK_L_DEVICE_ID];
                                                             [wrapParams setValue:[[[SuperSDKInst getInstance] clientInfo] valueForKey:DEVICE_VERSION] forKey:@"device_type"];
                                                             [wrapParams setValue:[[[SuperSDKInst getInstance] clientInfo] valueForKey:SSDK_L_IDFA] forKey:SSDK_L_IDFA];
                                                             [wrapParams setValue:[[[SuperSDKInst getInstance] clientInfo] valueForKey:APP_INNER_VERSION] forKey:APP_INNER_VERSION];
                                                             [wrapParams setValue:[[[SuperSDKInst getInstance] clientInfo] valueForKey:OS_VERSION] forKey:OS_VERSION];
                                                             [SSDKHttpV2Util postWithUrl:url data:wrapParams httpDelegate:^(BOOL status, NSDictionary *resData) {
                                                                 NSLog(@"上报心跳:%@", status?@"ok":@"fail");
                                                             }];
                                                         }];
    }];
}

- (void) stop {
    if (!self.isRunning || timer == nil) {
        return;
    }
    NSLog(@"心跳停止");
    [SSDKPluginTimerUtil stopTimer:timer];
    timer = nil;
    self.isRunning = NO;
}

@end
